package com.xiaoshuidi.cloud.module.iot.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoshuidi.cloud.module.iot.dal.mapper.DeviceDoMapper;
import com.xiaoshuidi.cloud.module.iot.dal.model.callback.AikeDeviceCallbackResVO;
import com.xiaoshuidi.cloud.module.iot.dal.model.device.TbDeviceDosageCallbackModel;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDeviceDo;
import com.xiaoshuidi.cloud.module.iot.dal.pojo.TbDeviceDosageDo;
import com.xiaoshuidi.cloud.module.iot.dal.repository.DeviceRepository;
import com.xiaoshuidi.cloud.module.iot.enums.BrandEnum;
import com.xiaoshuidi.cloud.module.iot.service.AikeCallbackService;
import com.xiaoshuidi.cloud.module.iot.service.LocalCallbackService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;

@Service
public class AikeCallbackServiceImpl implements AikeCallbackService {

    private Logger LOGGER = LoggerFactory.getLogger(AikeCallbackServiceImpl.class);

    @Autowired
    private DeviceRepository deviceDoMapper;

    @Autowired
    private LocalCallbackService localCallbackService;

    @Autowired
    private AikeCallbackService aikeCallbackService;

    @Override
    public void disposeCallback(TbDeviceDo tbDeviceDo) {
        deviceDoMapper.updateDeviceDoByThirdId(tbDeviceDo.getDeviceThirdNo());
    }

    @Override
    public AikeDeviceCallbackResVO getMeterReading(JSONObject object) {
        LOGGER.info("艾科水电回调请求，请求内容:{}", JSONObject.toJSONString(object));
        AikeDeviceCallbackResVO callbackResVO = new AikeDeviceCallbackResVO();
        try{
            Date currentTime = new Date();
            if (object.getJSONArray("data").size() > 0) {
                JSONArray dataList = object.getJSONArray("data");
                for (Iterator<Object> dataIterator = dataList.iterator(); dataIterator.hasNext(); ) {
                    TbDeviceDosageCallbackModel tbDeviceDosageCallbackModel = new TbDeviceDosageCallbackModel();
                    TbDeviceDosageDo tbDeviceDosageDo = new TbDeviceDosageDo();
                    TbDeviceDo tbDeviceDo = new TbDeviceDo();
                    JSONObject dataJson = (JSONObject) dataIterator.next();
                    String errMsg = dataJson.getString("ErrMsg");
                    String errNo = dataJson.getString("ErrNo");
                    //设备唯一标识
                    String meterCode = dataJson.getString("meterCode");
                    if("成功".equals(errMsg) && "0".equals(errNo)){
                        tbDeviceDo.setDeviceThirdNo(meterCode);
                        tbDeviceDo.setBrandNo(BrandEnum.AIKE.getBrand());
                        //在线
                        tbDeviceDo.setOnlineStatus(1);
                        tbDeviceDo.setPowerStatus(1);
                        tbDeviceDo.setBatteryLevel(100.00);
                        //读取时间
                        tbDeviceDosageDo.setCreateTime(LocalDateTime.now());
                        tbDeviceDosageDo.setUpdateTime(LocalDateTime.now());
                        String catCode = dataJson.getString("catCode");
                        JSONObject dataTiny = dataJson.getJSONObject("data");
                        switch (catCode){
                            case "水表" :
                                //当前水表读数
                                String accumulateFlux = dataTiny.getString("AccumulateFlux");
                                tbDeviceDosageDo.setEndAmount(Double.parseDouble(accumulateFlux));
                                //阀门状态
                                String valveStatus = dataTiny.getString("ValveStatus");
                                break;
                            case "电表" :
                                //当前电表读数,某些电表读数返回ElecValue，某些返回PositiveElec
                                String elecValue = dataTiny.getString("ElecValue");
                                String positiveElec = dataTiny.getString("PositiveElec");
                                if(null != elecValue){
                                    tbDeviceDosageDo.setEndAmount(Double.parseDouble(elecValue));
                                }
                                if(null != positiveElec){
                                    tbDeviceDosageDo.setEndAmount(Double.parseDouble(positiveElec));
                                }
                                //阀门状态
                                String switchState = dataTiny.getString("switchState");
                                // 0合闸 1拉闸
                                if(StringUtils.isNotEmpty(switchState)){
                                    if(switchState.equals("0")){
                                        tbDeviceDo.setPowerStatus(1);
                                    }else{
                                        tbDeviceDo.setPowerStatus(0);
                                    }
                                }
                                break;
                        }
                        tbDeviceDosageCallbackModel.setTbDeviceDosageDo(tbDeviceDosageDo);
                        tbDeviceDosageCallbackModel.setTbDeviceDo(tbDeviceDo);
                        LOGGER.info("艾科水电推送数据，操作抄表记录参数:{}", tbDeviceDosageCallbackModel);
                        localCallbackService.disposeDeviceDosage(tbDeviceDosageCallbackModel);

                    }
                    if("15000".equals(errNo)){
                        tbDeviceDo.setDeviceThirdNo(meterCode);
                        //离线
                        tbDeviceDo.setOnlineStatus(0);
                        tbDeviceDo.setBatteryLevel(100.00);
                        tbDeviceDo.setPowerStatus(1);
                        LOGGER.info("艾科水电设备离线，修改tb_device表:{}", tbDeviceDo);
                        aikeCallbackService.disposeCallback(tbDeviceDo);
                    }
                }
            }
            callbackResVO.setCode("1");
        }catch (Exception e){
            callbackResVO.setCode("0");
            callbackResVO.setMsg("回调系统异常");
            LOGGER.info("艾科回调异常，异常信息:{}",e.getMessage());
        }
        return callbackResVO;
    }
}
